import CloudTable from "@/component/CloudTable";
import { TYPE_ENUMS, TYPE_OPTIONS } from "@/views/sys/menu/data";
import { page, del, batDel, save, edit } from "@/views/sys/menu/api";
import { useTable } from "@/hooks/useTable";
import { Button, message, Space, Tooltip, Select } from 'antd';
import { EditOutlined, DeleteOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { useFormDialog } from "@/hooks/useForm";
import FormModal from "@/component/FormModal";
import { useEffect, useState } from "react";

const Menu = () => {

    const [options, setOptions] = useState([{ label: '顶层菜单', value: '0' }]);

    // 表单项
    const menuItems = [
        {
            label: '父菜单',
            name: 'parentId',
            rules: [{ required: true, message: '请选择上级菜单' }],
            render: <Select
                showSearch
                allowClear
                placeholder="请选择上级菜单"
                optionFilterProp="label"
                filterOption={false}
                onSearch={(val) => onSearchMenuHandle(val)}
                options={options}
            />
        },
        {
            label: '名称',
            name: 'name',
            rules: [{ required: true, message: '请输入名称' }],
        },
        {
            label: '编码',
            name: 'code',
            rules: [{ required: true, message: '请输入编码' }],
        },
        {
            label: '图标',
            name: 'icon',
        },
        {
            label: '路由',
            name: 'path',
        },
        {
            label: '类型',
            name: 'type',
            render: <Select placeholder='请选择类型' options={TYPE_OPTIONS()} />,
            rules: [{ required: true, message: '请选择类型' }],
        },
        {
            label: '排序',
            name: 'sort',
        },
    ];

    // 表单提交回调
    const onMenuFormCallback = (model) => {
        menuForm.onSubmit(model, menuTable.onReload);
    }

    // 表单操作
    const menuForm = useFormDialog({
        title: '新增',
        width: 450,
        save: save,
        edit: edit,
        callback: onMenuFormCallback,
        items: menuItems,
    });

    // 表格列头
    const menuColumns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: 200,
            ellipsis: true,
        },
        {
            title: '编号',
            dataIndex: 'code',
            key: 'code',
            width: 135,
            ellipsis: true,
        },
        {
            title: '图标',
            dataIndex: 'icon',
            key: 'icon',
            width: 135,
            ellipsis: true,
        },
        {
            title: '排序',
            dataIndex: 'sort',
            key: 'sort',
            width: 135,
            ellipsis: true,
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            width: 135,
            ellipsis: true,
            render: (status) => TYPE_ENUMS[status] || ''
        },
        {
            title: '路由',
            dataIndex: 'path',
            key: 'path',
            width: 'auto',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'id',
            width: 130,
            align: 'center',
            fixed: 'right',
            render: (val, row) => {
                return (
                    <div>
                        <Tooltip title="编辑">
                            <Button type="text" size="small" icon={<EditOutlined />} style={{ margin: '0 4px', color: 'blue' }} onClick={() => menuForm.isOpenDialog(row, '编辑')} />
                        </Tooltip>
                        <Tooltip title="添加子菜单">
                            <Button type="text" size="small" icon={<PlusCircleOutlined />} style={{ margin: '0 4px', color: 'blue' }} onClick={() => onAddFormDialog(row)} />
                        </Tooltip>
                        <Tooltip title="删除">
                            <Button type="text" size="small" icon={<DeleteOutlined />} style={{ margin: '0 4px', color: 'red' }} onClick={() => onRemoveHandler(row)} />

                        </Tooltip>
                    </div>
                )
            }
        }
    ];

    // 表格工具栏
    const menuTools = () => {
        return (
            <Space>
                <Button type="primary" onClick={() => onAddFormDialog()}>新增</Button>
                <Button type='dashed' style={{ color: 'red' }} onClick={() => onBatchRemoveHandler()}>删除</Button>
            </Space>
        );
    }

    // 表格操作
    const menuTable = useTable({
        columns: menuColumns,
        tools: menuTools,
        reload: page,
        remove: del,
        batchRemove: batDel
    });

    const onSearchMenuHandle = (val) => {
        let query = { params: [{ field: 'name', expr: 'LIKE_LEFT', value: val }] };
        page(query).then(resp => {
            let options = resp?.data?.records.map(item => ({
                label: item.name,
                value: item.id,
            }));
            if (!val) {
                options.unshift({ label: '顶层菜单', value: '0', });
            }
            setOptions(options);
        });
    }

    // 单个删除
    const onRemoveHandler = (row) => {
        if (row?.children?.length > 0) {
            menuTable.onBatchRemove(getTreeIds([row]), '确定要删除这条数据及其子数据吗？');
        } else {
            menuTable.onRemove(row.id);
        }
    }

    // 批量删除
    const onBatchRemoveHandler = () => {
        let ids = getTreeIds(menuTable.selectedRows);
        if (menuTable.selectedRows.length === ids.length) {
            menuTable.onBatchRemove(ids);
        } else {
            message.warning('有未删除的子数据！');
        }
    }

    // 获取所有id（父类及子类需要删除的id）
    const getTreeIds = (rows) => {
        let set = new Set();
        if (rows?.length > 0) {
            rows.forEach(item => {
                set.add(item.id);
                if (item.children?.length > 0) {
                    getTreeIds(item.children).forEach(each => set.add(each));
                }
            });
        }
        return [...set];
    }

    const onAddFormDialog = (row = undefined) => {
        if (row) {
            // 添加子菜单
            setOptions([{ label: row.name, value: row.id }]);
        } else {
            // 新增菜单
            setOptions([{ label: '顶层菜单', value: '0' }]);
        }
        // 打开弹窗
        menuForm.isOpenDialog({ parentId: row?.id || '0' }, '新增');
    }

    useEffect(() => {
        menuTable.onReload();
    }, []);

    return (
        <div>
            <CloudTable props={menuTable} />
            <FormModal props={menuForm} />
        </div>
    );
}

export default Menu;